package main

import (
	"fmt"
	"github.com/gorhill/cronexpr"
	"time"
)

type CronJob struct {
	expr *cronexpr.Expression
	nextTime time.Time
}

func main() {
	var (
		cronJob *CronJob
		expr *cronexpr.Expression
		now time.Time
		scheduleTable map[string]*CronJob // 调度表
	)

	now = time.Now()
	scheduleTable = make(map[string]*CronJob)

	// 任务1
	expr = cronexpr.MustParse("*/5 * * * * * *")
	cronJob = &CronJob{
		expr:expr,
		nextTime:expr.Next(now),
	}
	scheduleTable["job1"] = cronJob // 任务注册到调度表

	// 任务2
	expr = cronexpr.MustParse("*/5 * * * * * *")
	cronJob = &CronJob{
		expr:expr,
		nextTime:expr.Next(now),
	}
	scheduleTable["job2"] = cronJob // 任务注册到调度表


	go func() {
		var (
			jobName string
			cronJob *CronJob
			now time.Time
		)
		for {
			now = time.Now()
			for jobName,cronJob = range scheduleTable{
				// 判断是否到时间执行
				if cronJob.nextTime.Before(now) || cronJob.nextTime.Equal(now){
					go func(jobName string) {
						fmt.Println("执行",jobName)
					}(jobName)

					// 下次执行时间
					cronJob.nextTime =  cronJob.expr.Next(now)
					fmt.Println(jobName,"下次执行时间",cronJob.nextTime)
				}
			}
			// 睡眠100毫秒 , 等价 time.Sleep(100* time.Millisecond)
			select {
			case <-time.NewTimer(100*time.Millisecond).C:
			}
		}
	}()

	// 避免主线程退出
	time.Sleep(100*time.Second)
}
